package com.yupi.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.model.dto.chart.ChartAddRequest;
import com.yupi.springbootinit.model.dto.chart.ChartEditRequest;
import com.yupi.springbootinit.model.dto.chart.ChartQueryRequest;
import com.yupi.springbootinit.model.dto.chart.ChartUpdateRequest;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.ChartVO;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/chart")
public class ChartController {
    @Resource
    private ChartService chartService;
    @Resource
    private UserService userService;
    
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        // 转换
        BeanUtils.copyProperties(chartAddRequest, chart);
        List<String> chartDatas = chartAddRequest.getChartDatas();
        if (chartDatas != null){
            chart.setChartData(JSONUtil.toJsonStr(chartDatas));
        }
        chartService.validChart(chart, true);// 校验 不符合抛异常
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);// 保存
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();// 获取id selectKey
        return ResultUtils.success(newChartId);
    }
    
    @PostMapping("/delete")
    public BaseResponse<List<Boolean>> deleteChart(@RequestBody DeleteRequest deleteRequest , HttpServletRequest request) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (deleteRequest.getId() > 0 || !deleteRequest.getIds().isEmpty()) {
            User user = userService.getLoginUser(request);
            Long id = deleteRequest.getId();
            List<Long> ids = deleteRequest.getIds();
            if (id != null && id > 0) {
                if (!ids.contains(id)) {
                    ids.add(id);
                }
            }
            List<Boolean> results = new ArrayList<>();
            ids.forEach((Long item)->{
                //判断是否存在
                Chart chart = chartService.getById(item);
                ThrowUtils.throwIf(chart == null, ErrorCode.NOT_FOUND_ERROR);
                //判断是否为当前用户
                if (!chart.getUserId().equals(user.getId()) && !userService.isAdmin(request)){
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
                }
                results.add(chartService.removeById(item));
            });
            return ResultUtils.success(results);
        }else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
    }
    
    /**
     * 更新(仅限管理员)
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest, HttpServletRequest request) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);   
        }
        Chart chart = new Chart();
        // 转换
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        List<String> chartDatas = chartUpdateRequest.getChartDatas();
        if (chartDatas != null){
            chart.setChartData(JSONUtil.toJsonStr(chartDatas));
        }
        // 校验
        chartService.validChart(chart, false);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }
    /**
     * 根据id查询
     */
    @GetMapping("/get/vo")
    public BaseResponse<ChartVO> getChartVO(long id, HttpServletRequest request) {
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chartService.getChartVO(chart,request));
    }
    
    /**
     * 分页查询
     */
    @GetMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest ) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }
    
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ChartVO>> listChartVoByPage(@RequestBody ChartQueryRequest chartQueryRequest , HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartService.getChartVOPage(chartPage,request));
    }
    
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ChartVO>> listMyPostVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }
    
    // endregion
    
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<ChartVO>> searchPostVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.searchFromEs(chartQueryRequest);
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }
    
    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPost(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        List<String> tags = chartEditRequest.getChartDatas();
        if (tags != null) {
            chart.setChartData(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        chartService.validChart(chart, false);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }
    
}
